package com.fadadianqi.logistics.search;

import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.search.AbstractSearcher;
import com.fadadianqi.search.Argument;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.Utils;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.highlight.Highlighter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GoodsSearcher extends AbstractSearcher {

    @Override
    protected Argument initializtionArgument(String keyword,
                                             Pagination pagination) {
        Argument argument = Argument.getInstance();
        argument.setPagination(pagination);
        argument.setArgs("props", keyword, Occur.SHOULD, 0.99F);
        argument.setArgs(Goods.PROP_BRAND_NAME, keyword, Occur.SHOULD, 0.6F);
        argument.setArgs(Goods.PROP_CATEGORY_NAME, keyword, Occur.SHOULD, 0.6F);
        argument.setArgs(Goods.PROP_NAME, keyword, Occur.SHOULD, 0.9F);
        argument.setArgs(Goods.PROP_DISPLAY_NAME, keyword, Occur.SHOULD, 0.8F);

        if (!Utils.isLetter(keyword)) {
            String pinyin = StringHelper.toPinyin(keyword);
            argument.setArgs("pinyin", pinyin, Occur.SHOULD, 0.5F);
        } else {
            argument.setArgs("pinyin", keyword, Occur.SHOULD, 0.5F);
        }
        return argument;
    }

    @Override
    protected Object documentToVO(IndexSearcher searcher, Document doc,
                                  Highlighter highlighter) throws IOException {
        GoodsVO goods = new GoodsVO();
        goods.setId(doc.get(Goods.PROP_ID));
        goods.setBrandId(doc.get(Goods.PROP_BRAND_ID));
        goods.setCategoryId(doc.get(Goods.PROP_CATEGORY_ID));
        goods.setName(doc.get(Goods.PROP_NAME));
        goods.setDisplayName(doc.get(Goods.PROP_DISPLAY_NAME));
        return goods;
    }

    @Override
    protected String getIndexPath() {
        return goodsIndexService.getCurrentIndexPath();
    }

    @Autowired
    private GoodsIndexService goodsIndexService;

    public class GoodsVO extends Goods {

        /**
         *
         */
        private static final long serialVersionUID = 8135826982744961681L;

    }

}
